package org.shunfeng.controller;

import org.shunfeng.pojo.SysUser;
import org.shunfeng.service.UserService;
import org.shunfeng.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/user/changepassword")
public class ChangePassword extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");

            SysUser sysUser= (SysUser)req.getSession().getAttribute("user");
            Integer uId = sysUser.getId();
            String oldPassword = req.getParameter("password");
            String newPassword = req.getParameter("newpassword");

            SysUser user = userService.confirmPassword(Integer.toString(uId), oldPassword);
            if (user == null) {
                req.setAttribute("message", "原密码错误");
            } else {
                System.out.println("user  = " + user.toString());
                int i = userService.updatePassword(Integer.toString(uId), newPassword);
                if (i > 0) {
                    req.setAttribute("message", "修改成功");
                } else {
                    req.setAttribute("message", "修改失败");
                }
            }
            req.getRequestDispatcher("/password.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
